package com.mengchengnet.chaperonage.ui.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.mengchengnet.chaperonage.R;
import com.mengchengnet.chaperonage.adapter.OrderAdapter;
import com.mengchengnet.chaperonage.domain.base.Order;
import com.mengchengnet.chaperonage.util.DateUtils;
import com.mengchengnet.chaperonage.util.PreferenceUtil;
import com.mengchengnet.chaperonage.util.Url;
import com.mengchengnet.chaperonage.util.ViewUtil;
import com.mengchengnet.chaperonage.view.refreshableListView.RefreshableListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class CommentOrderFragment extends Fragment {
    private View view;

    private RefreshableListView rlvOrder;
    private OrderAdapter orderAdapter;
    private ArrayList<Order> orderList;
    private static final String TAG = "CommentOrderFragment";
    private RequestQueue requestQueue;
    private String userId;
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            orderAdapter = new OrderAdapter(getContext(), R.layout.item_order_listview, orderList);
            rlvOrder.setPullLoadEnable(false);
            rlvOrder.setPullRefreshEnable(true);
            rlvOrder.setAdapter(orderAdapter);
            rlvOrder.setRefreshableListViewListener(new RefreshableListView.RefreshableListViewListener() {
                @Override
                public void onRefresh() {
                    orderList.clear();
                    getOrder();
                    orderAdapter.notifyDataSetChanged();
                    rlvOrder.setRefreshTime(DateUtils.getNow());
                    rlvOrder.stopRefresh();

                }

                @Override
                public void onLoadMore() {

                }
            });
//            rlvOrder.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//                @Override
//                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//
//                    Intent intent = new Intent(getActivity(), OrderDetailActivity.class);
//                    startActivity(intent);
//                    getActivity().overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
////                String url = HttpInterface.URL_MAIN_BASE + "/wap/business/" + merchantAdapter.getItem(position - 1).getMerchantId();
////                Intent intent = new Intent(BaseActivity.currentActivity, MerchantDetailActivity.class);
////                intent.putExtra("url", url);//
////                BaseActivity.currentActivity.startActivity(intent);
//                }
//            });
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        setHasOptionsMenu(true);
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        if (view == null) {
            view = inflater.inflate(R.layout.fragment_all_order, null);
        }
        requestQueue= Volley.newRequestQueue(getContext());
        userId= PreferenceUtil.getString(getContext(),"userId");
        rlvOrder = (RefreshableListView) view.findViewById(R.id.lv_order);
        orderList = new ArrayList<>();


        ViewGroup parent = (ViewGroup) view.getParent();
        if (parent != null) {
            parent.removeView(view);
        }

        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!userId.isEmpty()){
            getOrder();
        }
    }

    private void getOrder() {
        ViewUtil.showProgressDialog("加载中...");
        StringRequest request = new StringRequest(Request.Method.POST, Url.GetUserOrderList,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String result) {
                        Log.e("订单界面", "待评价订单接口返回值："+result);
                        JSONObject jsonObject;
                        try {
                            if(result != null && result.startsWith("\ufeff"))
                            {
                                result =  result.substring(1);
                            }

                            jsonObject = new JSONObject(result);
                            if (jsonObject.getString("code").equals("00")){
                                ViewUtil.hideProgressDialog();
                                JSONArray array=jsonObject.getJSONArray("orderList");
                                for (int i = 0; i <array.length() ; i++) {
                                    JSONObject object=array.getJSONObject(i);
                                    String progress=object.getString("progress");
                                    String totalMoney=object.getString("totalMoney");
                                    String startTime=object.getString("startTime");
                                    String unit_price=object.getString("unit_price");
                                    String ServiceName=object.getString("ServiceName");
                                    String icon=object.getString("icon");
                                    String personId=object.getString("personId");

                                    Log.e(TAG, "订单状态: "+progress );
                                    Order order = new Order();
                                    order.setChaperonagePhoto(icon);
                                    order.setBusinessType("陪护");
                                    order.setChaperonageName(ServiceName);
                                    order.setOrderState(progress);
                                    order.setPrice(unit_price+"/天");
                                    order.setTotalPrice(totalMoney);
                                    order.setServeTime(startTime);
                                    order.setUserId(personId);
                                    orderList.add(order);

                                }
                                handler.sendEmptyMessage(0);
                            }
                            else {

                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError arg0) {

            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("loginId",userId);
                map.put("status","3");

                return map;
            }
        };
        request.setTag("GetFenZu");
        request.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, // 默认超时时间，应设置一个稍微大点儿的
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, // 默认最大尝试次数
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        requestQueue.add(request);

    }


}
